package util;

import org.apache.commons.dbutils.DbUtils;
import po.Course;

import java.lang.reflect.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DaoRepeat<T> {

    public boolean executeSQL(String sql, Object... obj) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = DBUtils.getConnection();
            ps = con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            int i = ps.executeUpdate();
            if (i > 0) {
                return true;
            } else {
                return false;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(null, ps, con);
        }
        return false;
    }

    public String getStringExecuteSQL(String parameter, String sql, Object... obj) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = DBUtils.getConnection();
            ps = con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                String string = rs.getString(parameter);
                return string;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(null, ps, con);
        }
        return null;
    }
    public  int getNumber(String sql, Object... obj)
    {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            rs = ps.executeQuery();
            int count=0;
            if (rs.next()){
                count++;
                return  count;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
return  0;
    }


    public int getIntExecuteSQL(String id, String sql, Object... obj) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = DBUtils.getConnection();
            ps = con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                int anInt = rs.getInt(id);
                return anInt;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(null, ps, con);
        }
        return -1;
    }


}


